import fs from 'fs'
import { fileURLToPath } from 'url'


// 找到指定目录下的所有控制器文件
export const getControllers = function () {
  // 第一步拿到控制器所在目录的绝对地址
  let controllersUrl = new URL('../controllers', import.meta.url).href;
  let filePath = fileURLToPath(controllersUrl);

  let files = fs.readdirSync(filePath);
  let controllerFiles = files.filter(item => item.endsWith('Controllers.js'));
  let controllerPath = controllerFiles.map(item => `${controllersUrl}/${item}`)
  return controllerPath;
}

//批量注册动态导入的模块中的路由
export const regControllers=function(router,controllerFiles){

    controllerFiles.forEach(async item => {
      let arr=await import(item)
      arr.default.forEach(obj=>{
        if(obj.method === 'get'){
          router.get(obj.url,obj.fn)
        }
        if (obj.method === 'post') {
          router.post(obj.url, obj.fn)
        }
        if (obj.method === 'put') {
          router.put(obj.url, obj.fn)
        }
        if (obj.method === 'del') {
          router.delete(obj.url, obj.fn)
        }
      })
    });
}


